from __future__ import annotations

from datetime import date, datetime
from typing import List, Optional

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import func
from sqlmodel import Session, select

from app.core.db import get_session
from .model import Reminder, ReminderCreate, ReminderRead, ReminderUpdate
from .service import update_reminders


router = APIRouter(prefix="/reminders", tags=["reminders"])


def _compute_derived_fields(reminder: Reminder) -> None:
    # 留空的派生字段在前端也可计算，这里简单占位以保持字段存在
    if reminder.anniversary_date:
        today = date.today()
        years = today.year - reminder.anniversary_date.year
        reminder.years_passed = max(0, years)


@router.post("/", response_model=ReminderRead)
def create_reminder(payload: ReminderCreate, session: Session = Depends(get_session)) -> ReminderRead:
    reminder = Reminder.model_validate(payload)
    session.add(reminder)
    session.commit()
    session.refresh(reminder)
    update_reminders(session, reminder)
    return ReminderRead.model_validate(reminder)


@router.put("/{reminder_id}", response_model=ReminderRead)
def update_reminder(reminder_id: int, payload: ReminderUpdate, session: Session = Depends(get_session)) -> ReminderRead:
    reminder = session.get(Reminder, reminder_id)
    if reminder is None:
        raise HTTPException(status_code=404, detail="Reminder not found")
    update_data = payload.model_dump(exclude_unset=True)
    for key, value in update_data.items():
        setattr(reminder, key, value)
    session.add(reminder)
    session.commit()
    session.refresh(reminder)
    update_reminders(session, reminder)
    return ReminderRead.model_validate(reminder)


@router.get("/", response_model=dict)
def read_reminders(page: int = 1, limit: int = 10, session: Session = Depends(get_session)) -> dict:
    if page < 1:
        page = 1
    if limit < 1:
        limit = 10
    offset = (page - 1) * limit
    total = session.exec(select(func.count()).select_from(Reminder)).one()
    items = session.exec(select(Reminder).offset(offset).limit(limit)).all()
    for r in items:
        _compute_derived_fields(r)
    return {"items": items, "total": total, "page": page, "page_size": limit}


@router.get("/{reminder_id}", response_model=ReminderRead)
def read_reminder(reminder_id: int, session: Session = Depends(get_session)) -> ReminderRead:
    reminder = session.get(Reminder, reminder_id)
    if reminder is None:
        raise HTTPException(status_code=404, detail="Reminder not found")
    _compute_derived_fields(reminder)
    return ReminderRead.model_validate(reminder)


@router.put("/{reminder_id}/toggle", response_model=ReminderRead)
def toggle_reminder_activation(reminder_id: int, session: Session = Depends(get_session)) -> ReminderRead:
    reminder = session.get(Reminder, reminder_id)
    if reminder is None:
        raise HTTPException(status_code=404, detail="Reminder not found")
    reminder.is_active = not reminder.is_active
    session.add(reminder)
    session.commit()
    session.refresh(reminder)
    _compute_derived_fields(reminder)
    return ReminderRead.model_validate(reminder)


@router.delete("/{reminder_id}")
def delete_reminder(reminder_id: int, session: Session = Depends(get_session)) -> dict:
    reminder = session.get(Reminder, reminder_id)
    if reminder is None:
        raise HTTPException(status_code=404, detail="Reminder not found")
    session.delete(reminder)
    session.commit()
    return {"ok": True}


